#----------------------------------------------------------------------------
#	Name: comic.py
#	Author: Doug Russell
#	Last Modified: 02-10-2008
#	Created with Python 2.5.2
#	Description: Functions for unzipping and unraring comic book archives
#	and a function to create a web gallery from the decompressed images
#	Requires Rarfile
#	Requires Python Image Library
#----------------------------------------------------------------------------
#	Copyright (C) 2008 Doug Russell
#	
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import division           # Adds floating point division
import os, sys, re, string, rarfile, zipfile
#from PIL import Image                     # Adds Image module
if sys.platform == 'win32':
	import UnRAR

subber = re.compile(r"[^A-Za-z0-9-_\.]").sub

class DirectoryWalker:
	# a forward iterator that traverses a directory tree
	def __init__(self, directory):
		self.stack = [directory]
		self.files = []
		self.index = 0
	
	def __getitem__(self, index):
		while 1:
			try:
				file = self.files[self.index]
				self.index = self.index + 1
			except IndexError:
				# pop next directory from stack
				self.directory = self.stack.pop()
				self.files = os.listdir(self.directory)
				self.index = 0
			else:
				# got a filename
				fullname = os.path.join(self.directory, file)
				if os.path.isdir(fullname) and not os.path.islink(fullname):
					self.stack.append(fullname)
				return fullname
	

def UnZipDir(dir, file):
	os.mkdir(dir, 0777)
	zfobj = zipfile.ZipFile(file)
	for name in zfobj.namelist():
		if name.endswith('/'):
			os.mkdir(os.path.join(dir, name))
		else:
			outfile = open(os.path.join(dir, name), 'wb')
			outfile.write(zfobj.read(name))
			outfile.close()

def PathSplitter(path):
	if os.name == 'posix':
		split_dir = string.split(path, '/')
		parent = string.join(split_dir[0:-1], '/')
		cwd = split_dir[-1]
	elif sys.platform == 'win32':
		print 'Untested'
		split_dir = string.split(filename, '\\')
		parent = string.join(split_dir[0:-1], '\\')
		cwd = split_dir[-1]
	return [parent, cwd]

def UnZipFile(dir, file):
	zfobj = zipfile.ZipFile(file)
	for name in zfobj.namelist():
		if name.endswith('/'):
			os.mkdir(os.path.join(dir, name))
		else:
			outfile = open(os.path.join(dir, name), 'wb')
			outfile.write(zfobj.read(name))
			outfile.close()

def UnRarComic(file):
	check = 0
	x = rarfile.RarFile(os.path.join(os.getcwd(), file))
	foldername = '_'
	for name in x.namelist():     # This will fail
		if name.find('\\') != -1: # if a archive has more than one directory
			foldername = name[0:name.find('\\')]
			check = 1
	f1 = file[0:-4]
	f2 = subber("", file[0:-4])
	f3 = foldername
	f4 = subber("", foldername)
	if os.path.exists(os.path.join(os.getcwd(), f1)) | \
	os.path.exists(os.path.join(os.getcwd(), f2)) | \
	os.path.exists(os.path.join(os.getcwd(), f3)) | \
	os.path.exists(os.path.join(os.getcwd(), f4)):
		print file[0:-4] + ' already exist, this will be skipped'
	else:
		print 'Decompressing ' + file
		if check == 1:
			if os.name == 'posix':
				os.system("unrar x -inul \"" + file + "\"")
			elif sys.platform == 'win32':
				try:
					UnRAR.Archive(file).extract()
				except:
					'God Damn Your Face Winders'
			try:
				os.rename(os.path.join(os.getcwd(), foldername), \
				os.path.join(os.getcwd(), file[0:-4]))
			except:
				print file[0:-4] + ' already exists, this will be skipped'
				os.remove(os.path.join(os.getcwd(), foldername))
		else:
			if os.name == 'posix':
				os.system("unrar x -ad -inul \"" + file + "\"")
			elif sys.platform == 'win32':
				try:
					UnRAR.Archive(file).extract()
				except:
					print 'God Damn Your Face Winders'

def UnZipComic(file):
	check = 0
	x = zipfile.ZipFile(os.path.join(os.getcwd(), file))
	foldername = '_'
	for name in x.namelist():
		if name.endswith('/'):
			foldername = name[0:name.find('\\')]
			check = 1
	f1 = file[0:-4]
	f2 = subber("", file[0:-4])
	f3 = foldername
	f4 = subber("", foldername)
	if os.path.exists(os.path.join(os.getcwd(), f1)) | \
	os.path.exists(os.path.join(os.getcwd(), f2)) | \
	os.path.exists(os.path.join(os.getcwd(), f3)) | \
	os.path.exists(os.path.join(os.getcwd(), f4)):
		print file[0:-4] + ' already exists, this will be skipped'
	else:
		print 'Decompressing ' + file
		if check == 1:
			UnZipFile(os.getcwd(), file)
			try:
				os.rename(os.path.join(os.getcwd(), foldername), \
				os.path.join(os.getcwd(), file[0:-4]))
			except:
				print file[0:-4] + ' already exist, this will be skipped'
				os.remove(os.path.join(os.getcwd(), foldername))
		else:
			UnZipDir(os.path.join(os.getcwd(), file[:-4]), file)

def RarComic(folder):
	if os.path.exists(os.path.join(os.getcwd(), folder + '.cbr')):
		print folder + '.cbr already exist, this will be skipped'
	else:
		if os.name == 'posix':
			print 'Attempting Compression'
			os.system("rar a -inul \"" + folder + ".cbr\" \"" + folder + "\"")
			print 'Compression Successful'
		elif sys.platform == 'win32':
			try:
				print 'Need to implement this'
				# do something with this
				#UnRAR.Archive(file).extract()
			except:
				'God Damn Your Face Winders'

def web_safe(directory):
	
	current = os.getcwd()
	os.chdir(directory)
	
	cwd = os.getcwd()
	while cwd.find('/') != -1:
		i = cwd.find('/')
		cwd = cwd[i+1:]
	
	displist = os.listdir(os.getcwd()) # List of files in current directories
	displist.sort()
	displist.append('-1')
	displistbak = []
	displistbak.extend(displist)
	
	k=0 # Loop to rename files
	while displist[k] != '-1':
		displist[k] = subber("", displist[k])
		displist[k] = string.lower(displist[k])
		os.rename(os.path.join(os.getcwd(), displistbak[k]), \
		os.path.join(os.getcwd(), displist[k]))
		k=k+1
	
	k=0 # Loop to remove non .jpg files
	while displist[k] != '-1':
		if displist[k].find('jpg') == -1:
			if displist[k].find('png') == -1:
				displist.pop(k)           # Remove current entry
			else:
				k=k+1
			
		else:                         # If it does
			k=k+1                     # Increment to next entry
		
	index = 1                         # Start loop to process each file
	displistnew = []
	displistnew.extend(displist)
	while displistnew[index] != '-1':
		
		im = Image.open(displistnew[index])
		wl = im.size
		if wl[0]/wl[1] > 1:
			im = im.rotate(-90)
		im.save(displistnew[index])
		
		index = index + 1 # End loop to process each file
	
	#------------------------------------------------------------------------
	
	os.chdir(current)
